package com.qj.yantaishan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qj.yantaishan.domain.ManageToPermission;
import com.qj.yantaishan.domain.Permission;
import com.qj.yantaishan.mapper.ManageToPermissionMapper;
import com.qj.yantaishan.mapper.PermissionMapper;
import com.qj.yantaishan.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Primary
public class IPermissionServiceImpl extends ServiceImpl<PermissionMapper,Permission> implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ManageToPermissionMapper manageToPermissionMapper;

    /**
     * 获取所有权限
     *
     * @return
     */
    @Override
    public List<Permission> selectPermissionAll() {
        //1.获取所有权限
        List<Permission> permissions = permissionMapper.selectList(new QueryWrapper<>());
        //2.拿出一级权限  fid==0
        List<Permission> fatherPermission = permissions.stream().filter(permission -> {
            return permission.getPermissionFid() == 0;
        }).collect(Collectors.toList());
        //2.拿每个父到全部中找他的子
        List<Permission> permissionList = fatherPermission.stream().map(f -> {
            //找它的子
            f.setChildPermissions(getChildPermission(f, permissions));
            return f;
        }).collect(Collectors.toList());
        return permissionList;
    }

    @Override
    public List<Map<String, Object>> getPermissionListByManageId(Object loginId) {
        return permissionMapper.selectPermissionByManageId(loginId);

    }

    @Override
    public void addManagePermssion(Integer id, Integer uid) {
        permissionMapper.addManagePermission(id, uid);
    }

    @Override
    public void deleteManagePermission(Integer uid) {
        permissionMapper.deleteManagePermission(uid);
    }

    private List<Permission> getChildPermission(Permission f, List<Permission> permissions) {
        List<Permission> collect = permissions.stream().filter(a -> {
            return f.getId() == a.getPermissionFid();
        }).collect(Collectors.toList());
        List<Permission> collect1 = collect.stream().map(c -> {
            c.setChildPermissions(getChildPermission(c, permissions));
            return c;
        }).collect(Collectors.toList());
        return collect1;
    }
}
